package io.kiki.sba.registry.util;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;


public final class CollectionUtils {
    private CollectionUtils() {
    }

    public static <E> E getRandom(List<E> list) {
        if (list.isEmpty()) {
            return null;
        }
        int idx = ThreadLocalRandom.current().nextInt(list.size());
        return list.get(idx);
    }

    public static <K, V> Map<K, V> toSingletonMap(Map<K, V> map) {
        if (map.size() != 1) {
            return map;
        }
        Map.Entry<K, V> one = map.entrySet().iterator().next();
        return Collections.singletonMap(one.getKey(), one.getValue());
    }

    public static <T> int fuzzyTotalSize(Collection<T> items, SizeGetter<T> sizeGetter) {
        if (org.springframework.util.CollectionUtils.isEmpty(items)) {
            return 0;
        }
        int maxPerSize = 0;
        int samples = 3;
        for (T item : items) {
            maxPerSize = Math.max(sizeGetter.getSize(item), maxPerSize);
            samples--;
            if (samples <= 0) {
                break;
            }
        }
        return maxPerSize * items.size();
    }

    public interface SizeGetter<T> {
        int getSize(T t);
    }
}
